<?php
ini_set('display_error', 'on');
$menu = 1;
$type = '등록';
if($_GET['id']) {
    $type = "수정";
}
$title = "선생님 $type"; 

$g4_path = "../"; 
require_once ($g4_path.'common.php');
require_once ('./admin.head.php');
require_once ('./admin.lib.php');

$tpl->assign('type', $type);
$perPage = 10;
$_temp = $filename = $sqlWhere = $imagefile = NULL; 
$_datano = FALSE;
$_regcode = 'register';
$defDir = "../data/bookImg/"; //업로드 될 디렉토리
$defFileType = array('jpg', 'gif', 'jpeg', 'png'); // 업로드 허용 파일 확장자들

if($_POST) { //등록,수정,삭제 시 처리
    $required = array(
        'mb_name'=> '이름',
        'mb_nick'=> '애칭',
        'mb_sex'=> '성별',
        'mb_id'=> 'ID',
        'mb_password' =>'비밀번호',
        'mb_jumin'=> '주민번호',
        'mb_zip1' => '우편번호',
        'mb_zip2' => '우편번호',
        'mb_addr1'=>'주소',
        'mb_addr2'=> '주소',
        'mb_birth'=>'생년월일',
        'mb_email'=> '이메일',
        'mb_tel'=> '연락처1',
        'mb_hp'=> '핸드폰',
        'mb_introduce'=>'자기소개',
        'mb_career'=> '경력',
    );
    requireProcess($required); //TODO

    if(!trim($_POST['mb_password'][0])) {
        alert('주민번호 항목은 필수입력항목입니다');
    }

    $toPutFields = array(
        'mb_code',
        'mb_name',
        'mb_nick',
        'mb_sex',
        'mb_id',
        'mb_password',
        'mb_jumin',
        'mb_zip1',
        'mb_zip2',
        'mb_addr1',
        'mb_addr2',
        'mb_birth',
        'mb_email',
        'mb_tel',
        'mb_tel2',
        'mb_hp',
        'mb_profile320',
        'mb_profile120',
        'mb_profile30',
        'mb_introduce',
        'mb_career',
        'mb_division',
        'mb_movie',
        'mb_level'
    );

    $_POST['mb_division'] = '강사';

    if($_POST['mb_password'][0] != $_POST['mb_password'][1]) {
        alert('비밀번호와 비밀번호 확인 항목은 반드시 같아야 합니다');
    } else {
        $_POST['mb_password'] = sql_password($_POST['mb_password'][0]);
    }

    $jumin = $mb_jumin;

    $row = sql_fetch("select mb_name, mb_profile320, mb_profile120, mb_profile30, mb_movie from $g4[member_table] where mb_jumin = '$jumin' ");
    if ($row['mb_name'] && $_POST['regcode'] == 'register') {
        if ($row['mb_name'] == $mb_name)
            alert("이미 가입되어 있습니다.");
        else
            alert("다른 이름으로 같은 주민등록번호가 이미 가입되어 있습니다.\\n\\n관리자에게 문의해 주십시오.");
    }

    foreach($_POST as $key => $val) {
        if(is_array($val)) {
            $_POST[$key] = implode('', $val);
        }
    }

    $teacherPictures = 'teacherPictures/';
    $teacherMovies = 'teacherMovies/';
    if($_FILES['mb_profile320']['name']) {
        $_POST['mb_profile320'] = $teacherPictures.fileUpload('mb_profile320', $teacherPictures, $defFileType );
    }
    if($_FILES['mb_profile120']['name']) {
        $_POST['mb_profile120'] = $teacherPictures.fileUpload('mb_profile120', $teacherPictures, $defFileType);
    }
    if($_FILES['mb_profile30']['name']) {
        $_POST['mb_profile30'] = $teacherPictures.fileUpload('mb_profile30', $teacherPictures, $defFileType);
    }
    if($_FILES['mb_movie']['name']) {
        $_POST['mb_movie'] = $teacherMovies.fileUpload('mb_movie', $teacherMovies, array('avi','wmv'));
    }

    switch($_POST['regcode']) {
        case 'modify': // 수정
            $toPutFieldNames = array_intersect(array_keys($_POST),($toPutFields));
            $put = array();
            foreach($toPutFieldNames as $key => $val) {
                $put[] = "$val = '".addslashes($_POST[$val])."'";
            }
            $put = implode(',', $put);
            $sql = "UPDATE g4_member SET  $put
                WHERE mb_no = {$_GET['mb_no']}";
            mysql_query($sql);

            break;
        case 'register': // 추가
            putDb('g4_member', $_POST, $toPutFields);
            $id = mysql_insert_id();
            $sql = "UPDATE g4_member SET mb_code = 'ka-$id' WHERE mb_no = $id";
            mysql_query($sql);

/*************그룹생성 및 게시판 생성 **************/

$_boardCreateId = $_POST['mb_id']; 
$gr_id = 't_'.$_boardCreateId; 
$gr_subject = $_boardCreateId.' 선생님의 그룹';
$bo_table = 't_'.$_boardCreateId; 
$bo_subject = $_boardCreateId.' 선생님의 게시판';
$$row = sql_fetch(" select count(*) as cnt from $g4[group_table] where gr_id = '$gr_id' ");
if ($row['cnt']) 
    alert("이미 존재하는 그룹 ID 입니다. 아이디를 다시 선택해주세요.");
$row = sql_fetch(" select count(*) as cnt from $g4[board_table] where bo_table = '$bo_table' ");
if ($row['cnt'])
    alert("{$bo_table} 은(는) 이미 존재하는 TABLE 입니다. 아이디를 다시 선택해 주세요.");

$sql_common = " gr_subject= '$gr_subject',gr_admin  = '$_boardCreateId',gr_use_access= '1'";
$sql = " insert into $g4[group_table]
 set gr_id = '$gr_id',$sql_common ";
sql_query($sql);
$board_path = "$g4[path]/data/file/$bo_table";
@mkdir($board_path, 0707);
@chmod($board_path, 0707);
$file = $board_path . "/index.php";
$f = @fopen($file, "w");
@fwrite($f, "");
@fclose($f);
@chmod($file, 0606);
$gr_id = 't_'.$_boardCreateId; 
$sql_common = " gr_id= '$gr_id',bo_subject = '$bo_subject',bo_admin= '$_boardCreateId',bo_list_level = '1',bo_read_level = '1',bo_write_level= '1',bo_reply_level= '1',bo_comment_level = '1',bo_html_level = '1',bo_link_level = '1',bo_trackback_level  = '1',bo_count_modify  = '1',bo_count_delete  = '1',bo_upload_level  = '$bo_upload_level',bo_download_level= '$bo_download_level',bo_read_point = '$bo_read_point',bo_write_point= '$bo_write_point',bo_comment_point = '$bo_comment_point',bo_download_point= '$bo_download_point',bo_use_category  = '1',bo_category_list = '',bo_disable_tags  = 'script|iframe',bo_use_sideview  = '$bo_use_sideview',bo_use_file_content = '$bo_use_file_content',bo_use_secret = '$bo_use_secret',bo_use_dhtml_editor = '$bo_use_dhtml_editor',bo_use_rss_view  = '$bo_use_rss_view',bo_use_comment= '$bo_use_comment',bo_use_good= '$bo_use_good',bo_use_nogood = '$bo_use_nogood',bo_use_name= '$bo_use_name',bo_use_signature = '$bo_use_signature',bo_use_ip_view= '$bo_use_ip_view',bo_use_trackback = '$bo_use_trackback',bo_use_list_view = '$bo_use_list_view',bo_use_list_content = '$bo_use_list_content',bo_use_email  = '$bo_use_email',bo_table_width= '97',bo_subject_len= '60',bo_page_rows  = '15',bo_new  = '24',bo_hot  = '100',bo_image_width= '600',bo_skin = 'qna',bo_include_head  = '../mydesk/board.include.php',bo_include_tail  = '../mydesk/board.tail.php',bo_content_head  = '$bo_content_head',bo_content_tail  = '$bo_content_tail',bo_insert_content= '$bo_insert_content',bo_gallery_cols  = '$bo_gallery_cols',bo_upload_count  = '2',bo_upload_size= '2097152',bo_reply_order= '1',bo_use_search = '1',bo_order_search  = '$bo_order_search',bo_write_min  = '$bo_write_min',bo_write_max  = '$bo_write_max',bo_comment_min= '$bo_comment_min',bo_comment_max= '$bo_comment_max',bo_sort_field = '$bo_sort_field',bo_1_subj  = '$bo_1_subj',bo_2_subj  = '$bo_2_subj',bo_3_subj  = '$bo_3_subj',bo_4_subj  = '$bo_4_subj',bo_5_subj  = '$bo_5_subj',bo_6_subj  = '$bo_6_subj',bo_7_subj  = '$bo_7_subj',bo_8_subj  = '$bo_8_subj',bo_9_subj  = '$bo_9_subj',bo_10_subj = '$bo_10_subj',bo_1 = '$bo_1',bo_2 = '$bo_2',bo_3 = '$bo_3',bo_4 = '$bo_4',bo_5 = '$bo_5',bo_6 = '$bo_6',bo_7 = '$bo_7',bo_8 = '$bo_8',bo_9 = '$bo_9',bo_10= '$bo_10' ";
$sql = " insert into $g4[board_table] set bo_table = '$bo_table', bo_count_write = '0', bo_count_comment = '0', $sql_common ";
sql_query($sql);
$file = file("../adm/sql_write.sql");
$sql = implode($file, "\n");
$create_table = $g4['write_prefix'] . $bo_table;
$source = array("/__TABLE_NAME__/", "/;/");
$target = array($create_table, "");
$sql = preg_replace($source, $target, $sql);
sql_query($sql, FALSE);

$mb_id = $_POST['mb_id']; 
$sql = "REPLACE INTO g4_group_member (`gr_id`, `mb_id`, `gm_datetime`) VALUES ('$gr_id', '$mb_id', '".$g4['time_ymdhis']."')";
sql_query($sql); 

/************그룹생성 및 게시판 생성 끝! *****************/
            break;
        case 'delete': // 삭제
            break;
        default:
            alert('오류 : 잘못된 접근입니다.', './bookManage.php'); 
    }
    //putDb('g4_member', array('mb_code' => 'ka-'.$id, 'mb_no'=>$id));
    
    switch($_POST['config']) {
        case 'add':
            goto_url('./teacher?add'); 
        break;
        case 'delete':
            alert('성공적으로 삭제되었습니다.', './bookManage.php'); 
        break;
        default:
            $page = 1; 
            if($_POST['datano']) {
                $res = sql_fetch("select count(*) as cnt from g4_member where no > ".$_POST['datano']." AND g4_division='강사'");
                $pageRet = $res[cnt]/$perPage+1;
                $page = (int)$pageRet;
            }
            goto_url('./members.php?division=teacher&condition=none&keyword=&button=%EA%B2%80%EC%83%89&page='.$page); 
    }
}

if(isset($_GET['mb_no'])) { //수정시 (id값이 넘어왔을때)
    $_regcode = 'modify';
    $data = getDb('g4_member', $_GET['mb_no'] ,'mb_no');
    $data['mb_introduce'] = htmlspecialchars($data['mb_introduce']);
    $data['mb_career'] = htmlspecialchars($data['mb_career']);
    $disabled = 'disabled  = "disabled"';
    if(!$data['mb_no']) {
        alert('자료가 존재하지 않습니다.');
    }
}

$tpl->define('basic',"teacher.html");
$tpl->print_('basic');
require_once('admin.foot.php');
